package com.gao.mybatis.resource;

import org.apache.commons.lang3.ClassUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2020-03-28 20:42
 */
public class ClassPathResources implements Resources {

    private final String path;

    private ClassLoader classLoader;

    private Class<?> clazz;


    public ClassPathResources(String path) {
        this(path, (ClassLoader) null);
    }

    public ClassPathResources(String path, ClassLoader classLoader) {
        this.path = path;
        this.classLoader = (classLoader != null ? classLoader : getDefaultClassLoader());
    }

    public ClassPathResources(String path, Class<?> clazz) {
        this.path = path;
        this.clazz = clazz;
    }


    public final String getPath() {
        return this.path;
    }

    public final ClassLoader getClassLoader() {
        return (this.clazz != null ? this.clazz.getClassLoader() : this.classLoader);
    }


    @Override
    public InputStream getInputStream() throws IOException {
        InputStream is;
        if (this.clazz != null) {
            is = this.clazz.getResourceAsStream(this.path);
        } else if (this.classLoader != null) {
            is = this.classLoader.getResourceAsStream(this.path);
        } else {
            is = ClassLoader.getSystemResourceAsStream(this.path);
        }
        if (is == null) {
            throw new FileNotFoundException(this.path+": not found");
        }
        return is;
    }

    public ClassLoader getDefaultClassLoader() {
        ClassLoader cl = null;
        try {
            cl = Thread.currentThread().getContextClassLoader();
        } catch (Throwable ex) {
        }
        if (cl == null) {
            cl = ClassUtils.class.getClassLoader();
            if (cl == null) {
                try {
                    cl = ClassLoader.getSystemClassLoader();
                } catch (Throwable ex) {
                }
            }
        }
        return cl;
    }

}
